\documentclass[dvipsnames]{article}
% \documentclass[dvipsnames]{ctexrep}
\usepackage{geometry}\geometry{
  a4paper,
  total={170mm,257mm},
  left=20mm,
  top=20mm,
}
\usepackage{adjustbox}          %to narrower the caption
\newlength\mylength
\usepackage{hyperref}
\usepackage{svg}
\usepackage[skip=5pt plus1pt, indent=0pt]{parskip}
\usepackage{emoji}
% \setemojifont{NotoColorEmoji.ttf}[Path=C:/Users/congj/repo/myFonts/]
% \setemojifont{TwitterColorEmoji-SVGinOT.ttf}[Path=C:/Users/congj/repo/myFonts/]


\usepackage{booktabs}
\input{h-lua}

\title{Weak Chain User Manual}
\date{\today}
\author{cccccje}
% \usepackage{fontspec}

\usepackage{fancyhdr}
\fancyhf{}                      % clear all header and footer fields
\lhead{\textnormal{\rightmark}}
% \rhead{--\ \thepage\ --}
\rfoot{--\ \thepage\ --}
\pagestyle{fancy}

\fancyfoot[C]{
  \begin{tikzpicture}[remember picture, overlay]
    % draw a corner at the top right
    \draw[fill=gray,draw=none,opacity=0.2] (current page.north east) -- +(-2,0) -- +(0,-6) -- cycle;
    \draw[fill=gray,draw=none,opacity=0.7] (current page.north east) -- +(-3,0) -- +(0,-4) -- cycle;
    \draw[fill=\mycola,draw=none,opacity=0.7] (current page.north east) -- +(-7,0) -- +(0,-3) -- cycle;


    % draw at the bottom left
    \draw[fill=gray,draw=none,opacity=0.6] (current page.south west) --
    +(7,0) -- +(0,2) -- cycle;
    \draw[fill=\mycola,draw=none,opacity=0.6] (current page.south west) --
    +(2,0) -- +(0,6) -- cycle;
    \draw[fill=gray,draw=none,opacity=0.3] (current page.south west) --
    +(3,0) -- +(0,4) -- cycle;
  \end{tikzpicture}
}

\newcommand{\Wch}{\strong{\cola{Weak Chain}}}

\begin{document}
\maketitle

\begin{center}
  \begin{tikzpicture}[every text node part/.style={align=center}]
    \node (test) [] {
      % \includesvg[width=0.8\linewidth]{logo.svg}
      \includegraphics[width=0.8\linewidth]{logo.png}
  };
\end{tikzpicture}
\end{center}

\tableofcontents{}
\newpage{}

\section{Welcome}
This is the user manual for \Wch{}. \Wch{} is a private
blockchain. The name come from the idea that
  \cola{
  ``you only need a weak understanding of blockchain
  in order to use it''
}. This manual includes some concepts and some tutorials.
It's hoped that following this manual, you will be able to get the most from its
features.

% In the hope of improving readability, this manual is written as Q\&A between our
% two characters, Coco the Parrot \emoji{parrot} and Tim the Turtle
% \emoji{turtle}.
% Coco is a student. He is curious but not very patient. He just
% wants to get things done, but he's not a big fan of becoming a blockchain
% expert. Tim is the teacher. He is more knowledgeable, and willing to share
% everything he knows, but meanwhile keeping things as simple as possible. Tim
% often get pissed off by Coco's impatience, but he knows that's just what he
% should deal with in order to be a good teacher.

% If you are ready, join the journey with Coco and Tim. Let's get started.

% \input{doc-concepts} % 🐢 : Let's postpone this for now.

\input{doc-tutorials}


\section{Features}
\label{sec:feat}

\subsection{Python Contract}
\label{sec:how-to-py}
\emoji{turtle} : In this section we talk about python contract. There're two
things that a user might need to know:
\begin{enumerate}
\item How to write a python contract
\item How to invoke a python contract
\end{enumerate}
We discuss them one by one here.
\subsubsection{How to write}

A python contract is a python file with some special rules. In particular, the
rules are
\begin{enumerate}
\item At the top level, only \texttt{import, import from} and \texttt{def} are
  allowed.
\item Only some imports are allowed.
\item Some identifiers are not allowed.
\item Optional arguments are not supported.
\end{enumerate}

\paragraph{Allowed imports}
The following imports are allowed:
\begin{longtblr}[caption = {Allowed imports of python contract},
  label = {tab:allowed-py-imports}
  ]%
  {colspec={XXX[3]},
    rowhead = 1, % first row is shown on every page
  }
  \toprule
  % Allowed_modules : list[str] = ['math', 'cmath', 'typing', 'hashlib', 'hmac']
  \mbox{Module} & \mbox{Allowed symbol} & \mbox{Description} \\
  \midrule
  \texttt{math} & * & standard math module \\
  \texttt{cmath} & * & complex number module \\
  \texttt{typing} & * & module for type hints \\
  \texttt{hashlib} & * & hash module \\
  \texttt{hmac} & * & hash-based message authentication code module \\
  \bottomrule
\end{longtblr}
So you write things like
\begin{simplepy}
import math
from math import sin
from typing import *
\end{simplepy}

But not
\begin{simplepy}
import os
\end{simplepy}

% ['__import__', 'breakpoint', 'compile', 'eval', 'execfile', \
% 'exec', 'get_ipython', 'globals', 'memoryview', 'help', \
% 'id', 'input', 'open', 'quit', 'exit', 'runfile', 'vars']

\paragraph{Identifiers}
The following identifiers are not allowed:
\begin{center}
  \ttfamily
  \begin{tblr}{colspec={ccccc},colsep=2em}
    \_\_import\_\_ & breakpoint & compile & eval & execfile \\
    exec & get\_ipython & globals & memoryview & help \\
    id & input & open & quit & exit \\
    runfile & vars & & & \\
  \end{tblr}
\end{center}
These cannot appear as identifier, which is pretty much everywhere except within
string literal and comments.

So you can't write things like
\begin{simplepy}
open('file.txt')
x.open('file.txt')
def open(x):
    pass

def f(open=2):
    pass
\end{simplepy}

However, there can be identifiers that contains the above strings. For example,
\begin{simplepy}
id0 = 123
\end{simplepy}

\paragraph{Contract Methods}

The top level \texttt{def} statement defines the invokable contract methods. A
minimal contract might look like
\begin{simplepy}
def hi() -> str:
    return "hi"
\end{simplepy}

About these methods, two things worth mentioning:
\begin{enumerate}
\item Special Arguments
\item The \texttt{init} method
\end{enumerate}

\paragraph{Special arguments}

Method arguments starting with an underscore are special arguments. They are
passed by the runtime, not the invoker. For example,
\begin{simplepy}
def set(key: str, value: Any, _storage: dict[str,Any]) -> None:
    _storage[key] = value

def get(key: str, _storage: dict[str,Any]) -> Any:
    return _storage[key]
\end{simplepy}

The above two methods have the special argument \texttt{\_storage}. This
represents the contract's storage. The runtime will prepare and pass the current
storage to the method. So to invoke the \texttt{set()} method, user only need to
give
\begin{simplejs}
{
    "method" : "set",
    "args" : {
        "key" : "k1",
        "value" : "v1"
    }
}
\end{simplejs}
as the invoke json.

These arguments have special meanings, but they are usally \texttt{dict()}
generated from a json string. In particular we have the following special
arguments:

\begin{itemize}
\item \texttt{\_storage} : the contract's storage. This is just a
  \texttt{dict()} object. And everything written to this object is dumped to
  json and persisted to the blockchain. If the the jsonization of it fails, the
  whole transaction will fail.(So nothing will be written to the blockchain)
\item \texttt{\_tx\_context} : the transaction context. This contains
  information about the current transaction. It is a \texttt{dict()} object with
  the following keys:
  \begin{center}
    \begin{tblr}{XXX[3]}
      \textbf{Key} & \textbf{Type} & \textbf{Description} \\
      \hline
      \texttt{from} & \texttt{str} & the sender's address in hex \\
      \texttt{to} & \texttt{str} & the receiver's address in hex. It can be
      empty if it's the deploying transaction.
      \colz{
        (\emoji{turtle} : This should
        only happens in the \texttt{init()} method. More on this later.)
      }\\
      \texttt{hash} & \texttt{str} & the transaction hash in hex \\
      \texttt{timestamp} & \texttt{int} & the timestamp of the transaction \\
      \hline
    \end{tblr}
  \end{center}
  % \begin{itemize}
  % \item \texttt{from} : the sender's address in hex : \texttt{str}
  % \item \texttt{to} : the receiver's address in hex : \texttt{str}
  % \item \texttt{hash} : the transaction hash in hex : \texttt{str}
  % \item \texttt{timestamp} : the timestamp of the transaction : \texttt{int}
  % \end{itemize}
\end{itemize}

Therefore, a method do things like:
\begin{simplepy}
def hi(_storage: dict[str,Any], _tx_context : dict[str,Any]) -> None:
    _storage["tx_from"] = _tx_context["from"]  # address hex string
    _storage["tx_to"] = _tx_context["to"]  # address hex string
    _storage["tx_hash"] = _tx_context["hash"]  # hex string
    _storage["tx_timestamp"] = _tx_context["timestamp"]  # int
\end{simplepy}



\paragraph{The \texttt{init()} method}
If a top-level method named \texttt{init()} is defined, it will be called when
when the contract is deployed. So it can be something like:
\begin{simplepy}
def init(_storage: dict[str,Any], _tx_context : dict[str,Any]) -> None:
    _storage["creater"] = _tx_context["from"]  # address hex string
\end{simplepy}

\emoji{turtle} : Below is a more involved contract that showcases some features.
\begin{simplepy}
from typing import Any
from math import sqrt

def hi() -> str:
    return "hi"

def plus_one(x : int) -> int:
    return x + 1

def set(key: str, value: Any, _storage: dict[str,Any]) -> None:
    _storage[key] = value

def get(key: str, _storage: dict[str,Any]) -> Any:
    return _storage[key]

def init(_storage: dict[str,Any], _tx_context : dict[str,Any]) -> None:
    _storage["tx_from"] = _tx_context["from"]  # address hex string
    _storage["tx_to"] = _tx_context["to"]  # address hex string
    _storage["tx_hash"] = _tx_context["hash"]  # hex string
    _storage["tx_timestamp"] = _tx_context["timestamp"]  # int
    # 🦜 : storage is a dictionary that should be serializable into JSON
\end{simplepy}

\subsubsection{How to invoke}
\emoji{turtle} : Conceptually, PyVM accepts an ``invoke json'' and returns a
result, when a contract method is invoked. The invoke json is something
like:

\begin{simplejs}
{
    'method' : 'plus_one',
    'args' : {'x' : 1}
}
\end{simplejs}

To pass that to PyVM, the recommended way is to first store it in a file, say
\texttt{/tmp/invoke.json}, and then use the \texttt{@} helper provided by
\Wch{}, which is something like:
\begin{simplesh}
txs='[{
    "from" : "01",
    "to" : "0000000000000000000000000000000064d05d1b",
    "data" : "@/tmp/tmp.json",
    "nonce" : 124,
    "type" : "python"
}]'
curl --data $txs http://localhost:7777/add_txs
# => "hash": "c63fce1da4f0a30c0ae6c8ce332286f188d71dc13638beca74fb5939c5a79ec8",
\end{simplesh}

The result can be any json serializable object. It can be a number, a string, an
array, or an object. And as shown in the tutorial in \cref{sec:pyvm}, the result
can be retrieved by something like:
\begin{simplesh}
curl "http://localhost:7777/get_receipt?hash=c63fce1da4f0a30c0ae6c8ce332286f188d71dc13638beca74fb5939c5a79ec8"
# {"ok":true,"result": 123}
\end{simplesh}
Here the result is 123.

\section{HTTP API}

User of \Wch{} can interact with the blockchain through HTTP API. They are
documented here.

\subsection{\texttt{POST /add\_txs}}
Add (send) an array of transactions to the blockchain. A transaction is a json
object, and it's a bit different according to different transaction modes. See 
see \cref{sec:secure-tx}. A transaction json can have the following forms:

\begin{enumerate}
\item \texttt{test tx-mode} Transaction

  If the chain is started in \texttt{test tx-mode}, 
  Then the transaction is a json object like:
  \begin{simplejs}
{
    "from" : "0000000000000000000000000000000000000001",
    "to" : "",
    "data": "ffff",
    "type" : "evm",
    "nonce" : 123
}
  \end{simplejs}
  Where \texttt{from} is the sender's address, \texttt{to} is the receiver's
  address. Address should be a 40-character hex string (leading zeros might be
  ommited, but must be a valid hex string), so 20 bytes long.

  \texttt{data} is the data of the transaction. It can be any string depending
  on the transaction type.

  \texttt{nonce} is the nonce of the transaction. It should unique for
  each sender. If \texttt{to} is empty, it's a deploying transaction. Otherwise,
  it's invoking a contract method of the contract at address \texttt{to}. One
  exception is the \cola{pure-data transaction}, where \texttt{to} doesn't
  matter, and the \texttt{data} is the data to be stored on the blockchain.

  If the \texttt{data} field starts with an \texttt{@}, it's assumed to be a
  file, and the content of the file is used as the data. This is usually used
  for python transaction, because it's a little awkward to put a python contract
  in a json string... Also, it can be used for pure data transaction, in which
  case user specify the file path in the \texttt{data} field, and the content of
  file can be any string.(But not binary data). The file path is relative to the
  working directory of the chain, if you are unsure, use an absolute path.
  
  \texttt{type} can be \texttt{evm} , \texttt{python} or \texttt{data}, which
  corresponds to EVM transaction, python transaction and pure data transaction
  respectively. When no \texttt{type} field is provided, it's assumed to be an
  EVM transaction.

  Note that in this form, user can specify who he/she is without signing the
  transaction.


  Example 1: Deploy a get/set 123 contract:
\begin{simplesh}

txs='[
  {"from" : "01",
   "to" : "",
   "data" : "608060405234801561001057600080fd5b50610150806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c806360fe47b11461003b5780636d4ce63c14610057575b600080fd5b610055600480360381019061005091906100c3565b610075565b005b61005f61007f565b60405161006c91906100ff565b60405180910390f35b8060008190555050565b60008054905090565b600080fd5b6000819050919050565b6100a08161008d565b81146100ab57600080fd5b50565b6000813590506100bd81610097565b92915050565b6000602082840312156100d9576100d8610088565b5b60006100e7848285016100ae565b91505092915050565b6100f98161008d565b82525050565b600060208201905061011460008301846100f0565b9291505056fea2646970667358221220271e30d641d99bedebb5450b18efe8b67269cf688a15386162d4c2ff7072a8af64736f6c63430008130033",
   "nonce" : 123
  }
]'
e=http://localhost
curl --data $txs $e:7777/add_txs
# [
#     {
#         "hash": "b06b89b665df6f7ff1be967faf9a0601f71c0a3cdb8250c48fe7fcc663b18d1b",
#         "deployed_address": "0000000000000000000000000000000064d05d1b"
#     }
# ]
\end{simplesh}

  Example 2: Invoke the \texttt{set} method of the contract at address
\begin{simplesh}
deployed_addr=0000000000000000000000000000000064d05d1b
txs="[
  {
  \"from\" : \"01\",
  \"to\" : \"$deployed_addr\",
   \"data\" : \"60fe47b1000000000000000000000000000000000000000000000000000000000000007b\",
   \"nonce\" : 125
  }
]"
e=http://localhost
curl --data $txs $e:7777/add_txs
# The result can be retrieved from the transaction receipt._
\end{simplesh}
\item \texttt{public tx mode} Transaction and \texttt{ca tx mode}

  If the chain is started in \texttt{public tx mode} or \texttt{ca tx mode}, then the transaction is a
  json object like:
\begin{simplejs}
{
  "type": "data",
  "to": "",
  "data": "hi",
  "nonce": 123,
  "signature": "ed70765d68dd2cadd5f728cf6c2eed40803248e650bd81728ea9cd4f31e340dff8139b54be520dd6f2b9568e17e68ac3820e46dfc4e1ad5cdf915b115e503402",
  "pk_pem": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAT47M3UrUIEwqtPzKox/9Ar5ouCxL1l8SjYbGHjBzEfk=\n-----END PUBLIC KEY-----\n"
}
\end{simplejs}
This is similar to the \texttt{test tx mode} transaction, but instead of
manually specifying the sender's address, the sender's address is derived from
the supplied public key.

\emoji{parrot} : How do I sign the transaction using my private key?

\emoji{turtle} : \Wch{} provides a tool for you, see \cref{sec:secure-tx} for
how did we use \texttt{wch toolbox} to sign a transaction (and do almost all the
cryptographic magic we need for using \Wch{})
  
\end{enumerate}




\subsection{\texttt{GET /get\_latest\_Blk}}

Get the $n$ latest block:
\begin{table}[h]
  \caption{Query Parameter of \texttt{GET /get\_latest\_Blk}}
  \centering
  \begin{tblr}{|X[1]|X[1]|X[3]|X[1]|}
    \hline
    \Cola{Query Param} & \Cola{Type} & \Cola{Description} & \Cola{Optional} \\
    \hline
    \texttt{n} & positive integer & get the latest \texttt{n} blocks on the chain.
    \texttt{n} defaults to 1& yes \\
    \hline
  \end{tblr}
\end{table}
% \FloatBarrier
\FloatBarrier                   % \usepackage{placeins}

Example:
\begin{simplesh}
# get the latest 2 blocks
curl http://localhost:7777/get_latest_blk?n=2
\end{simplesh}

\subsection{\texttt{GET /get\_receipt}}

Get the receipt of a transaction:

\begin{table}[h]
  \caption{Query Parameter of \texttt{GET /get\_receipt}}
  \centering
  \begin{tblr}{|X[1]|X[1]|X[3]|X[1]|}
    \hline
    \Cola{Query Param} & \Cola{Type} & \Cola{Description} & \Cola{Optional} \\
    \hline
    \texttt{hash} & hex string & the hash of the transaction in hex (so it
    should be 64-char long) & no \\
    \hline
  \end{tblr}
\end{table}

Example:
\begin{simplesh}
curl http://localhost:7777/get_receipt?hash=a46e1806155b08cf95763b2e2dabeebff40859727d07d457d75a23069a66ca15
\end{simplesh}

\subsection{\texttt{GET /get\_tx}}

Get the transaction by hash:

\begin{table}[h]
  \caption{Query Parameter of \texttt{GET /get\_tx}}
  \centering
  \begin{tblr}{|X[1]|X[1]|X[3]|X[1]|}
    \hline
    \Cola{Query Param} & \Cola{Type} & \Cola{Description} & \Cola{Optional} \\
    \hline
    \texttt{hash} & hex string & the hash of the transaction in hex (so it
    should be 64-char long) & no \\
    \hline
  \end{tblr}
\end{table}

Example:
\begin{simplesh}
curl http://localhost:7777/get_tx?hash=a46e1806155b08cf95763b2e2dabeebff40859727d07d457d75a23069a66ca15
\end{simplesh}

\subsection{\texttt{GET /get\_blk}}

Get the \texttt{n}th block:

\begin{table}[h]
  \caption{Query Parameter of \texttt{GET /get\_blk}}
  \centering
  \begin{tblr}{|X[1]|X[1]|X[3]|X[1]|}
    \hline
    \Cola{Query Param} & \Cola{Type} & \Cola{Description} & \Cola{Optional} \\
    \hline
    \texttt{n} & positive integer & the index of the block. & no \\
    \hline
  \end{tblr}
\end{table}

Example:
\begin{simplesh}
curl http://localhost:7777/get_blk?n=1
\end{simplesh}

\end{document}
% Local Variables:
% TeX-engine: luatex
% TeX-command-extra-options: "-shell-escape"
% TeX-master: "m.tex"
% TeX-parse-self: t
% TeX-auto-save: t
% End: